package com.openapi.common.utils;

import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class FileUtil {

	/**
	 * 文件后缀
	 *
	 * @param fileName
	 * @return
	 */
	public static String getFileSuffix(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
	}


	/**
	 * 文件复制
	 * @param in
	 * @param filePath
	 * @param fileName
	 */
	public static void copy(InputStream in, String filePath, String fileName) {
		File folder;
		String dir;
		FileOutputStream out = null;
		try {
			folder = new File(filePath);
			if (!folder.exists()) folder.mkdirs();
			dir = String.format("%s%s", filePath, fileName);
			out = new FileOutputStream(new File(dir));
			FileCopyUtils.copy(in, out);
		} catch (Exception e) {

		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null){
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				System.out.println("删除单个文件" + fileName + "成功！");
				return true;
			} else {
				System.out.println("删除单个文件" + fileName + "失败！");
				return false;
			}
		} else {
			System.out.println("删除单个文件失败：" + fileName + "不存在！");
			return false;
		}
	}

	public static String RenameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}
}
